﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using SimpleFS.Core;
using SimpleFS.Core.Implementations;

namespace SimpleFS.Services.Encryption
{
    public class File : AbstractFile
    {
        protected ICryptoTransform transform;

        public File(IFile internalObject, ICryptoTransform transform)
            : base(internalObject)
        {
            this.transform = transform;
        }

        #region IFile Members

        public System.IO.Stream Read()
        {
            System.IO.Stream stream = base.internalObject.Read();
            byte[] buffer = new byte[stream.Length];

            CryptoStream cryptoStream =
                new CryptoStream(
                    stream, this.transform, CryptoStreamMode.Read);

            int length = cryptoStream.Read(buffer, 0, (int)stream.Length);

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            length = cryptoStream.Read(buffer, 0, (int)cryptoStream.Length);
            memoryStream.Write(buffer, 0, length);

            stream.Close();

            return memoryStream;
        }

        public void Write(System.IO.Stream stream)
        {
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            CryptoStream encStream
                = new CryptoStream(
                    memoryStream, this.transform,
                    CryptoStreamMode.Write);

            byte[] buffer = new byte[stream.Length];

            stream.Read(buffer, 0, (int)stream.Length);
            encStream.Write(buffer, 0, (int)stream.Length);

            this.internalObject.Write(memoryStream);

            encStream.Close();
            memoryStream.Close();
        }

        #endregion
    }
}
